package com.eliza.base.views.device.position

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.widget.Toast
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.core.app.ActivityCompat
import androidx.navigation.NavController
import com.eliza.library.permission.PermissionUtils
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices

@Composable
fun PositionScreen(it: NavController) {
    val context = LocalContext.current

    Column {
        positionPermission(context)
        requestPosition(context)
    }
}

@Composable
private fun positionPermission(context: Context) {
    val arrayListOf = arrayOf(
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
    )
    LazyColumn {
        items(arrayListOf) {
            TextButton(onClick = {
                PermissionUtils.requestPermissions(
                    context as Activity,
                    1,
                    it
                )
            }) {
                Row {
                    Text(text = PermissionUtils.hasPermission(context, it).toString())
                    Text(text = "Click To requestPermissions")
                }

            }
        }
    }
}

@Composable
private fun requestPosition(context: Context) {
    val fusedLocationClient: FusedLocationProviderClient =
        LocationServices.getFusedLocationProviderClient(context)

    var location by remember { mutableStateOf("No location available") }


    TextButton(onClick = {
        if (ActivityCompat.checkSelfPermission(
                context,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                context,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            Toast.makeText(context,"no permission",Toast.LENGTH_SHORT).show()
        }
        fusedLocationClient.lastLocation
            .addOnSuccessListener { loc ->
                location = "Latitude: ${loc.latitude}, Longitude: ${loc.longitude}"
            }

    }) {
        Text(text = fusedLocationClient.lastLocation.result.toString())

    }

}